package com.army.onlineedict.slice;

import com.army.onlineedict.ResourceTable;
import com.army.onlineedict.common.MyDict;
import com.army.onlineedict.common.SearchWordCallback;
import com.army.onlineedict.common.WordData;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.system.DeviceInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    public final static int SEARCH_RESULT = 100;
    private MyDict myDict;
    private TextField textfieldWord;
    private Text textSearchResult;
    private Image imageSearch;
    private Image image;

    /**
     * 处理查询结果去向
     */
    private class SearchWordCallbackImpl implements SearchWordCallback {
        @Override
        public void onResult(List<WordData> result) {
            if (DeviceInfo.getDeviceType().equals("wearable")) {
                // 如果是智能手表，调用显示查询结果方法
                showSearchResult(result);
            } else {
                // 否则这里是TV，先获取主线程，
                EventRunner runner = EventRunner.getMainEventRunner();
                // 传递主线程处理显示查询结果
                MyEventHandler handler = new MyEventHandler(runner, result);
                // 发送Event
                handler.sendEvent(SEARCH_RESULT);
                runner = null;
            }
        }
    }

    /**
     * 自定义处理机制
     * EventHandler是一种用户在当前线程上投递InnerEvent事件或者Runnable任务到异步线程上处理的机制
     */
    public class MyEventHandler extends EventHandler {
        private List<WordData> wordDataList;

        public MyEventHandler(EventRunner runner, List<WordData> wordDataList) {
            super(runner);
            this.wordDataList = wordDataList;
        }

        // 回调函数查询结果
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (null == event) {
                return;
            }

            int eventId = event.eventId;
            // 判断相应的Event Id，处理相应事件
            switch (eventId) {
                case SEARCH_RESULT: {
                    if (wordDataList.size() == 0) {
                        textSearchResult.setText("单词没有查到，请确认单词是否输入错误！");
                    } else {
                        textSearchResult.setText("");
                        for (WordData wordData : wordDataList) {
                            textSearchResult.append(wordData.type + " " + wordData.meanings + "\r\n");
                        }
                    }
                    break;
                }
            }
        }
    }

    // 用于在智能手表中显示搜索结果的方法
    public void showSearchResult(List<WordData> result) {
        Intent intent = new Intent();
        ArrayList<String> typeList = new ArrayList<>();
        ArrayList<String> meaningList = new ArrayList<>();
        for (WordData wordData : result) {
            typeList.add(wordData.type);
            meaningList.add(wordData.meanings);
        }
        // 封装跳转到新页面的数据
        intent.setStringArrayListParam("typeList", typeList);
        intent.setStringArrayListParam("meaningList", meaningList);
        // 跳转到新的页面，并传intent
        present(new WearableSearchResultAbilitySlice(), intent);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        if (DeviceInfo.getDeviceType().equals("wearable")) {
            // 智能手表UI布局
            super.setUIContent(ResourceTable.Layout_wearable_ability_main);
        } else if (DeviceInfo.getDeviceType().equals("tv")) {
            // TV UI布局
            super.setUIContent(ResourceTable.Layout_tv_ability_main);
        }else {
            super.setUIContent(ResourceTable.Layout_ability_main);
        }

        myDict = new MyDict(this);
        try {
            // 初始化数据，并打开数据库
            myDict.init();
        } catch (IOException e) {
            // 退出程序
            terminateAbility();
        }

        // 获取XML布局组件
        textfieldWord = (TextField) findComponentById(ResourceTable.Id_textfield_word);
        textSearchResult = (Text) findComponentById(ResourceTable.Id_text_search_result);
        imageSearch = (Image) findComponentById(ResourceTable.Id_image_search);
        image = (Image) findComponentById(ResourceTable.Id_image);

        if (null != imageSearch) {
            imageSearch.setClickable(true);
            imageSearch.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    // 当前页面，只在TV才有图片LOGO和显示查询结果组件
                    if (DeviceInfo.getDeviceType().equals("tv") || DeviceInfo.getDeviceType().equals("default")) {
                        image.setVisibility(Component.HIDE);
                        textSearchResult.setVisibility(Component.VISIBLE);
                    }

                    List<WordData> result = myDict.searchLocalDict(textfieldWord.getText());
                    if (result.size() > 0) {
                        // 如果是智能手表，调用显示查询结果方法
                        if (DeviceInfo.getDeviceType().equals("wearable")) {
                            showSearchResult(result);
                        } else {
                            textSearchResult.setText("");
                            // 输出查询结果
                            for (WordData wordData : result) {
                                textSearchResult.append(wordData.type + " " + wordData.meanings + "\r\n");
                            }
                        }
                    }else {
                        if (DeviceInfo.getDeviceType().equals("tv") || DeviceInfo.getDeviceType().equals("default")) {
                            textSearchResult.setText("本地词库没有查到此单词, 正在查找网络词库...");
                        }
                        myDict.searchWebDict(textfieldWord.getText(), new SearchWordCallbackImpl());
                    }
                }
            });
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
